import { Button, Input } from "antd";
import React, { useRef, useState } from "react";

export default function index() {
  const container = useRef<any>(null);
  const [btnloading, setBtnLoading] = useState(false);
  const queue = useRef(Array.from({ length: 100000 }, () => performWorkUnit));

  function performWorkUnit() {
    let span = document.createElement("span");
    span.innerText = "1";
    container.current.appendChild(span);
  }

  const handleAddDom = () => {
    setBtnLoading(true);
    requestIdleCallback(workLoop);
  };
  const workLoop = () => {
    if (queue.current.length === 0) {
      return setBtnLoading(false);
    }
    let performWorkUnit: any;
    requestIdleCallback((deadline) => {
      if ((performWorkUnit = queue.current.pop()) && !deadline.didTimeout && deadline.timeRemaining() > 0) {
        performWorkUnit();
      }
      workLoop();
    });
  };

  function expensiveTask() {
    let i = 0;
    for (; i < 10000; i++) {
      let span = document.createElement("span");
      span.innerText = "1";
      container.current.appendChild(span);
    }
  }
  //高优先级任务
  function highPriority() {
    let span = document.createElement("span");
    span.innerText = "2";
    span.style.color = "red";
    container.current.appendChild(span);
  }

  return (
    <div className="space-y-4">
      <Button loading={btnloading} onClick={handleAddDom} type="primary">
        开启优化
      </Button>
      <Button className="ml-4" loading={btnloading} onClick={expensiveTask} type="primary">
        没有开启优化
      </Button>
      <Button className="ml-4" onClick={highPriority} type="primary">
        插入高优先级任务
      </Button>
      <Input />
      <div className=" break-words overflow-y-scroll " ref={container}></div>
    </div>
  );
}
